import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

// 路由切换滚动条配置
NProgress.configure({ showSpinner: false })

// 路由是否已初始化
var routerInitialized = false

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // 初始化路由
  if (!routerInitialized) {
    const accessRoutes = await store.dispatch('permission/generateRoutes', [])
    // console.log(accessRoutes)
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)
    // console.log('路由初始化完成')
    // eslint-disable-next-line require-atomic-updates
    routerInitialized = true
    // 添加完路由重定向重新匹配路由 解决刷新空白问题 replace为ture不留记录
    next({ ...to, replace: true })
    return
  }

  // // 验证通过
  // next()
  // return
  // console.log('from:', from)
  // console.log('to', to)
  // console.log('token:', store.getters.token)
  // console.log('authInfo:', store.getters.authInfo)

  // 验证页面是否存在
  if (!to.matched || to.matched.length === 0) {
    next({ path: '/404' })
    return
  }

  // 前往页面是否需要验证登陆和权限
  if (to.meta.validLogin) {
    if (!store.getters.token) {
      next({ path: '/login' })
      return
    }
    // 验证模块权限
    if (to.meta.validAction) {
      const checkPathAuth = (modules, enName) => {
        for (let i = 0; i < modules.length; i++) {
          const a = modules[i]
          if (a.enName.toLowerCase() === enName.toLowerCase()) {
            return true
          }
          if (a.children) {
            if (checkPathAuth(a.children, enName)) {
              return true
            }
          }
        }
        return false
      }
      // 验证模块权限 用最后一个匹配的路由寻找当前登录用户的有权限的模块
      const toName = to.matched[to.matched.length - 1].name
      if (!toName) {
        console.log('目标路由没有设置name：', to)
      }
      if (!checkPathAuth(store.getters.authInfo, toName)) {
        next({ path: '/401' })
        return
      }
    }
  }

  // 验证通过
  next()
  return
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
